package com.lmx.project.untils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.lmx.project.common.ErrorCode;
import com.lmx.project.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


/**
 * excle工具类
 */
@Component
public class ExcleUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcleUtils.class);

    //
    @Value("${myfile.pre}")
    private String pre;

    private String excledir = "excle/";

    /**
     * 参数fileName表示Excel文件路径，clazz表示待转换为的Java对象类型。
     * 使用EasyExcel.read()方法读取Excel文件，并提供回调函数实现解析Excel文件。
     * 将解析到的Java对象添加到resultList中，最后返回该List对象即可。
     */
    public <T> List<T> readExcel(InputStream fileinputstream, Class<T> clazz) {
        List<T> resultList = new ArrayList<>();
        try {
            // 读取Excel文件
            EasyExcel.read(fileinputstream, clazz, new AnalysisEventListener<T>() {

                @Override
                public void invoke(T t, AnalysisContext analysisContext) {
                    Class<?> aClass = t.getClass();

                    Field[] fields = t.getClass().getDeclaredFields();
//                    System.out.println("元素");
//                    System.out.println(t);
//                    System.out.println(Arrays.stream(fields).toArray());
                    for (Field field : fields) {
                        field.setAccessible(true);
                        Object o = null;
                        try {
                            o = field.get(t);
//                            System.out.println(o.toString());
                            String name = field.getName();
//                            如果字段名称是remark则可以为空
                            if (!name.equals("remark")) {
                                if (o == null) {
                                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "请检查您的表格是否含有空数据");
                                }
                            }

                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                            throw new BusinessException(ErrorCode.PARAMS_ERROR, "表格数据错误");
                        }

//                        System.out.println(field.getName()+"："+o)
                    }
                    resultList.add(t);

                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    LOGGER.info("Excel解析完成。");
                }
            }).sheet().doRead();

            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件读取失败,请确保上传的excle表符合模板要求");
        }

    }

    /**
     * 创建一个指定对象的表格,返回结果路径
     *
     * @param tClass
     */
    public <T> String CreateTableByContact(Class<T> tClass, String name) {
// 创建 ExcelWriter 对象

        try {
//            String filename = this.pre + excledir + tClass.getSimpleName() + ".xlsx";
            String filename = this.pre + excledir + name + ".xlsx";
            File file = new File(filename);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }

            ExcelWriter build = EasyExcel.write(file, tClass).build();
            WriteSheet sheet = EasyExcel.writerSheet().build();

//            T t = tClass.getConstructor().newInstance();
            ArrayList<Object> objects = new ArrayList<>();
            build.write(objects, sheet);
            build.finish();

            return filename;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
//
    }


    /**
     * 创建一个指定对象的表格,返回结果路径,增加下拉效果
     *
     * @param tClass
     */
    public <T> String CreateTableByContactAndPullDown(Class<T> tClass, SheetWriteHandler sheetWriteHandler, String name) {
// 创建 ExcelWriter 对象

        try {
//            String filename = this.pre + excledir + tClass.getSimpleName() + ".xlsx";
            String filename = this.pre + excledir + name + ".xlsx";
            File file = new File(filename);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }

            ExcelWriter build = EasyExcel.write(file, tClass).build();
            WriteSheet sheet = EasyExcel.writerSheet().registerWriteHandler(sheetWriteHandler).build();

//            T t = tClass.getConstructor().newInstance();
            ArrayList<Object> objects = new ArrayList<>();
            build.write(objects, sheet);
            build.finish();

            return filename;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
//
    }


    /**
     * 判断是否是excle表格文件
     */
    public boolean isExcelFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();

        String substring = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
        if (substring.contains("xlsx") || substring.contains("xls")) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
//        ExcelUtils excelUtils = new ExcelUtils();
//        excelUtils.CreateTableByContact();
//        List<ContactExcleVo> contactExcleVos = excelUtils.readExcel("test.xlsx", ContactExcleVo.class);
//        System.out.println(contactExcleVos);
    }
}